<?php
declare (strict_types=1);

namespace app\exam\logic\admin;

use app\common\exception\LogicException;
use app\exam\model\admin\ModulePointCates as ModulePointCatesModel;
use app\common\model\category\Category;

/**
 * Class ModulePointCates
 *
 * @package app\exam\logic\admin
 */
class ModulePointCates extends ModulePointCatesModel
{

    public function updateCates($moduleId)
    {
        $moduleCates = app(ModulePoint::class)->where('module_id', $moduleId)->field('fullcategorypath')->select()->toArray();
        $moduleCates = array_column($moduleCates, 'fullcategorypath');

        $cates       = [];
        foreach ($moduleCates as $mcs) {
            foreach($mcs as $mc) {
                $cates[] = $mc;
            }
            $lastCate = end($mcs);
            $allChild = $this->getAllChildIds($lastCate);
            if (count($allChild)) {
                foreach($allChild as $c) {
                    $cates[]= $c;
                }
            }
        }
        $cates = array_values(array_unique($cates));

        $data = $this->where('module_id', $moduleId)->findOrEmpty();
        if ($data->isEmpty()) {
            // 创建
            $this::create([
                'module_id' => $moduleId,
                'cates'     => $cates
            ]);
        } else {
            // 更新
            $data->cates = $cates;
            $data->save();
        }
    }

    public function getAllChildIds($pid)
    {
        app(Category::class)->setCategoryType(3);
        $child = app(Category::class)->wherePid($pid)->column('id');

        if (!count($child)) return $child;

        foreach($child as $c) {
            $cids = $this->getAllChildIds($c);
            if (count($cids)) $child = array_merge($child, $cids);
        }
        return $child;
    }
}